package com.xiang.reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiang.reggie.common.Result;
import com.xiang.reggie.dto.DishDto;
import com.xiang.reggie.entity.Category;
import com.xiang.reggie.entity.Dish;
import com.xiang.reggie.entity.DishFlavor;
import com.xiang.reggie.service.CategoryService;
import com.xiang.reggie.service.DishFlavorService;
import com.xiang.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜品管理
 *
 * @author 半山居雾
 * @date 2022/12/15 20:34
 */

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto 菜dto
     * @return {@code Result<String>}
     */
    @PostMapping()
    public Result<String> save(@RequestBody DishDto dishDto) {

        dishService.saveWithFlavor(dishDto);

        //清空redis中缓存的菜品数据
        Long categoryId = dishDto.getCategoryId();
        redisTemplate.delete("dish-"+categoryId);

        return Result.success("添加菜品成功");
    }

    /**
     * 查询菜品
     *
     * @param page     页面
     * @param pageSize 页面大小
     * @param name     名字
     * @return {@code Result<Page>}
     */
    @GetMapping("/page")
    public Result<Page> queryByPage(Integer page, Integer pageSize, String name) {
        //1.构造分页对象
        Page<Dish> dishPage = new Page<>(page, pageSize);
        //用来将分类id获取为名称的对象
        //通过对象拷贝
        Page<DishDto> dishDtoPage = new Page<>();


        //2.条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(dishPage, queryWrapper);

        //对象拷贝  (不拷records因为这个dish数据里没有分类名称，需要将dish数据加上分类名称变成dishDto拷贝进去)
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        //获取dish对象数据
        List<Dish> records = dishPage.getRecords();
        //获取分类名称
        List<DishDto> list = records.stream().map((item) -> {
            //dishDto 没有dish的数据，需要将item拷贝进去
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        return Result.success(dishDtoPage);
    }


    /**
     * 查询通过id展示数据
     *
     * @param id id
     * @return {@code Result<DishDto>}
     */
    @GetMapping("/{id}")
    public Result<DishDto> queryById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return Result.success(dishDto);
    }


    /**
     * 更新
     *
     * @param dishDto 菜dto
     * @return {@code Result<String>}
     */
    @PutMapping()
    public Result<String> update(@RequestBody DishDto dishDto) {

        dishService.updateWithFlavor(dishDto);

        //清空redis中缓存的菜品数据
        Long categoryId = dishDto.getCategoryId();
        redisTemplate.delete("dish-"+categoryId);

        return Result.success("修改菜品成功");
    }

    /**
     * 删除由ids(单个或者批量)
     *
     * @param ids id
     * @return {@code Result<String>}
     */
    @DeleteMapping()
    public Result<String> deleteByIds(Long[] ids) {

        //删除菜品加口味
        for (Long id : ids) {
            dishService.removeById(id);
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, id);
            if (dishFlavorService.getMap(queryWrapper) != null) {
                dishFlavorService.remove(queryWrapper);
            }
        }

        //清空redis中缓存的菜品数据
        Set keys = redisTemplate.keys("dish-*"); //获取所有以dish-xxx开头的key
        redisTemplate.delete(keys); //删除这些key

        return Result.success("删除成功");
    }

    /**
     * 更新状态(起停)
     *
     * @param status 状态
     * @param ids    id
     * @return {@code Result<String>}
     */
    @PostMapping("/status/{status}")
    public Result<String> updateStatus(@PathVariable int status, Long[] ids) {
        LambdaUpdateWrapper<Dish> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.set(Dish::getStatus, status);
        queryWrapper.in(Dish::getId, ids);
        boolean update = dishService.update(queryWrapper);

        return update ? Result.success("修改状态成成功") : Result.error("修改状态失败");
    }


    /**
     * 添加套餐展示菜品数据
     *
     * @param categoryId 菜
     * @return {@code Result<List<DishDto>>}
     */

    @GetMapping("/list")
    public Result<List<DishDto>> list(Long categoryId) {

        //优化1：先从redis中获取当前分类下的菜品数据
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get("dish-" + categoryId);

        if (dishDtoList != null) {
            //redis中缓存了当前分类下的菜品数据
            return Result.success(dishDtoList);
        }

        //redis中没有缓存当前分类下的数据，需要进行持久层操作，查询MySQL中的数据

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(categoryId != null, Dish::getCategoryId,categoryId);
        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> dishList = dishService.list(queryWrapper);
        dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Long dishCategoryId = item.getCategoryId();
            String name = categoryService.getById(dishCategoryId).getName();
            if (name != null) {
                dishDto.setCategoryName(name);
            }

            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
            qw.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> flavorList = dishFlavorService.list(qw);
            dishDto.setFlavors(flavorList);
            return dishDto;
        }).collect(Collectors.toList());

        //优化2：将MySQL中查询到的菜品数据缓存到redis中
        redisTemplate.opsForValue().set("dish-"+categoryId,dishDtoList);


        return Result.success(dishDtoList);
    }


}
